package de.micromata.icalour;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Print dynamic RSS to client
 * Set imageMode to imageServletUrl to generate a dynamic image, after the request
 * Set imageMode to imageFilePath to save the image to the file system and 
 */
public class RssServlet extends HttpServlet {

	private static final long serialVersionUID = -7489952775617464755L;
	private static Logger LOG = Logger.getRootLogger();
	private String absoluteURL = null;
	private final String imageServletUrl = "generateImage";
	private final String imageFilePath = "image.jpg";
	private final String imageMode = imageFilePath;
	private String defaultPort = "8080"; // default

	/**
	 * Default constructor.
	 */
	public RssServlet() {
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException {

		LOG.info("rss port: " + request.getServerPort());

		// set header information
		response.setContentType("application/rss+xml");
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
		response.setHeader("Pragma", "no-cache"); // HTTP 1.0
		response.setDateHeader("Expires", 0); // prevents caching at the proxy server

		Context env;
		String httpPort = null;
		try {
			env = (Context)new InitialContext().lookup("java:comp/env");
			httpPort = (String)env.lookup("httpPort");
		} catch (NamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		if (httpPort == null || httpPort.equals("")) {
			httpPort = defaultPort;
		}
		absoluteURL = request.getScheme() + "://" + request.getServerName() + ":"	+ httpPort + request.getContextPath() + "/";

		// call ImageServlet, generate image and save it to the file system
		if (imageMode.equals(imageFilePath)) {
			URLConnection con = null;
			try {
				con = new URL(absoluteURL + imageServletUrl + "?dynamic=off&file="+imageFilePath).openConnection();
				con.connect();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		// write content of the Media RSS to the client
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
			out.print("<rss version=\"2.0\" xmlns:media=\"http://search.yahoo.com/mrss/\" >\n");
			out.print("<channel>\n");
			out.print("<title>iCalOur Channel</title>\n");
			out.print("<link>http://www.micromata.de</link>\n");
			out.print("<description>Showing the latest meetings a micromatas meeting room</description>\n");
			out.print("<ttl>1</ttl>\n");
			out.print("<item>\n");
			out.print("<title>Latest Meeting(s)</title>\n");
			// print link and description for a preview of the image in the browser
			out.print("<link>" + absoluteURL + imageMode + "</link>\n");
			out.print("<description>&lt;img src=&quot;" + absoluteURL + imageMode	+ "&quot;&gt;</description>\n");
			out.print("<guid isPermaLink=\"false\">" + new Date().getTime()	+ "</guid>\n");
			// set the link to the image (ImageServlet)
			out.print("<media:content url=\"" + absoluteURL + imageMode	+ "\" type=\"image/jpeg\" width=\"800\" height=\"480\"/>\n");
			out.print("</item>\n");
			out.print("</channel>\n");
			out.print("</rss>\n");
			out.flush();
		} catch (IOException e) {
			LOG.error("could not get writer from response");
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}
